package com.cn.kabalifeuser.ui.integral.activity;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.cn.kabalifeuser.R;
import com.cn.kabalifeuser.base.IBaseActivity;
import com.cn.kabalifeuser.config.LoginHelper;
import com.cn.kabalifeuser.ui.integral.adapter.CommodityCommentListAdapter;
import com.cn.kabalifeuser.ui.integral.adapter.CommodityParamsAdapter;
import com.cn.kabalifeuser.ui.integral.adapter.SpecArrAdapter;
import com.cn.kabalifeuser.ui.integral.adapter.SpecArrItemsAdapter;
import com.cn.kabalifeuser.ui.integral.bean.CommodityCommentListBean;
import com.cn.kabalifeuser.ui.integral.bean.ContentCustBean;
import com.cn.kabalifeuser.ui.integral.bean.DetailsInfoBean;
import com.cn.kabalifeuser.ui.integral.bean.OrderPlaceBean;
import com.cn.kabalifeuser.ui.integral.bean.OrderSetBean;
import com.cn.kabalifeuser.ui.login.bean.MsgBean;
import com.cn.kabalifeuser.ui.service.activity.BusinessHomeCommentListActivity;
import com.cn.kabalifeuser.ui.service.adapter.DetailsCommentListAdapter;
import com.cn.kabalifeuser.utils.GlideImageLoader;
import com.cn.kabalifeuser.utils.GlideUtil;
import com.cn.kabalifeuser.utils.LoggerUtils;
import com.cn.kabalifeuser.utils.RxToast;
import com.cn.kabalifeuser.utils.StringUtil;
import com.cn.kabalifeuser.view.FlowLayoutManager1;
import com.cn.kabalifeuser.view.LCardView;
import com.cn.kabalifeuser.view.PopupWindow.CommonPopupWindow;
import com.cn.kabalifeuser.view.PopupWindow.CommonUtil;
import com.cn.kabalifeuser.view.SpaceItemDecoration;
import com.flyco.roundview.RoundTextView;
import com.google.android.material.appbar.AppBarLayout;
import com.umeng.commonsdk.debug.W;
import com.youth.banner.Banner;
import com.zzhoujay.richtext.RichText;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by 晓林 on 2020/9/12.
 * function: 积分商品主页
 */
public class IntegralCommodityDetailsActivity extends IBaseActivity<IntegralCommodityDetailsView, IntegralCommodityDetailsPresenter> implements IntegralCommodityDetailsView, CommonPopupWindow.ViewInterface {


    Bundle bundle;
    int id;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.fl_layout)
    FrameLayout flLayout;
    @BindView(R.id.appbar)
    AppBarLayout appbar;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_attr1)
    TextView tvAttr1;
    @BindView(R.id.tv_attr2)
    TextView tvAttr2;
    @BindView(R.id.tv_attr3)
    TextView tvAttr3;
    @BindView(R.id.tv_spec)
    TextView tvSpec;
    @BindView(R.id.ll_comment)
    LCardView llComment;
    @BindView(R.id.tv_content)
    TextView tvContent;
    @BindView(R.id.rv_comments)
    RecyclerView rvComments;
    @BindView(R.id.tv_act_title)
    TextView actTitle;
    @BindView(R.id.tv_comment_num)
    TextView tvCommentNum;
    @BindView(R.id.tv_btn_add_cart)
    RoundTextView tv_btn_add_cart;


    private CommonPopupWindow popupWindowSpecifications, popupWindowParams;

    DetailsInfoBean detailsInfoBean;


    int num = 1;//数量
    int store_count = 0;//库存
    int spec_id = 0;//规格id

    OrderSetBean orderSetBean;//选择的某一个规格，


    List<CommodityCommentListBean.ResultBean.DataBean> mList;
    CommodityCommentListAdapter mAdapter;


    int isCartBug = 1;//1是购买 2：是加入购物车


    @Override
    protected IntegralCommodityDetailsPresenter createPresenter() {
        return new IntegralCommodityDetailsPresenter();
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_commodity_details;
    }


    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        bundle = getIntent().getExtras();
        id = bundle.getInt("id");


        appbar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
//                float percent = Float.valueOf(Math.abs(verticalOffset)) / Float.valueOf(appBarLayout.getTotalScrollRange());
                //第一种
                int toolbarHeight = appBarLayout.getTotalScrollRange();
                int dy = Math.abs(verticalOffset);
                if (dy <= toolbarHeight) {
                    float scale = (float) dy / toolbarHeight;
                    float alpha = scale * 255;
                    flLayout.setBackgroundColor(Color.argb((int) alpha, 249, 140, 103));
//                    tvTitle.setTextColor(Color.argb((int) alpha, 0, 0, 0));
                }
                //第二种
            }
        });
        mList = new ArrayList<>();
        LinearLayoutManager layoutManager = new LinearLayoutManager(getMe());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        layoutManager.setSmoothScrollbarEnabled(true);
        layoutManager.setAutoMeasureEnabled(true);
        rvComments.setLayoutManager(layoutManager);
        rvComments.setNestedScrollingEnabled(false);
        //创建适配器
        mAdapter = new CommodityCommentListAdapter(R.layout.commodity_comment_item, mList, this);
        //给RecyclerView设置适配器
        rvComments.setAdapter(mAdapter);

        mPresenter.onDetailsData(LoginHelper.getLonginData().getResult(), id);

        mPresenter.onDetailsCommentsData(LoginHelper.getLonginData().getResult(), id);
    }

    @Override
    public void onReLoggedIn(String msg) {
        RxToast.error(msg);
        LoginHelper.againGoToLoginActivity(getMe());
    }

    @Override
    public void onError(String msg) {
        RxToast.error(msg);
        finish();
    }

    @Override
    public Context _getContext() {
        return null;
    }

    @Override
    public void onDetailsSuccess(DetailsInfoBean bean) {
        detailsInfoBean = bean;
        banner.setImageLoader(new GlideImageLoader());
        //设置图片集合
        banner.setImages(bean.getResult().getImg());
        //动画效果
        //banner.setBannerAnimation(Transformer.Accordion);
        //banner设置方法全部调用完毕时最后调用
        banner.start();
        tvTitle.setText(bean.getResult().getTitle());
        tvMoney.setText(bean.getResult().getMoney());
        actTitle.setText(bean.getResult().getAct_title());


//        tvAttr
        if (bean.getResult().getAttr_arr() != null && bean.getResult().getAttr_arr().size() > 0) {
            if (bean.getResult().getAttr_arr().size() >= 3) {
                tvAttr1.setVisibility(View.VISIBLE);
                tvAttr2.setVisibility(View.VISIBLE);
                tvAttr3.setVisibility(View.VISIBLE);
                tvAttr1.setText(bean.getResult().getAttr_arr().get(0).getIs_key());
                tvAttr2.setText(bean.getResult().getAttr_arr().get(1).getIs_key());
                tvAttr3.setText(bean.getResult().getAttr_arr().get(2).getIs_key());
            } else if (bean.getResult().getAttr_arr().size() == 2) {
                tvAttr1.setVisibility(View.VISIBLE);
                tvAttr2.setVisibility(View.VISIBLE);
                tvAttr3.setVisibility(View.GONE);
                tvAttr1.setText(bean.getResult().getAttr_arr().get(0).getIs_key());
                tvAttr2.setText(bean.getResult().getAttr_arr().get(1).getIs_key());
            } else if (bean.getResult().getAttr_arr().size() == 1) {
                tvAttr1.setVisibility(View.VISIBLE);
                tvAttr2.setVisibility(View.GONE);
                tvAttr3.setVisibility(View.GONE);
                tvAttr1.setText(bean.getResult().getAttr_arr().get(0).getIs_key());
            }
        }
        RichText.from(bean.getResult().getContent()).autoFix(false).showBorder(false).autoPlay(true).into(tvContent);
    }

    @Override
    public void onOrderSuccess(OrderPlaceBean bean) {

        if (popupWindowSpecifications != null)
            popupWindowSpecifications.dismiss();
        //提交訂單
        List<OrderSetBean> list = new ArrayList<>();
        list.add(orderSetBean);
        Bundle bundle = new Bundle();
        bundle.putSerializable("ListOrderSetBeans", (Serializable) list);
        bundle.putString("s_moneyAll", bean.getResult().getTotal_amount());
        bundle.putString("s_num", bean.getResult().getGood_num());
        bundle.putInt("sign", 1);
        $startActivity(OrderConfirmActivity.class, bundle);
        orderSetBean = null;
        tvSpec.setText("");
        tv_btn_add_cart.getDelegate().setBackgroundColor(getResources().getColor(R.color.text_dddddd));


    }

    @Override
    public void onDetailsCommentsSuccess(CommodityCommentListBean bean) {

        if (bean.getResult().getData() != null && bean.getResult().getData().size() > 0) {
            rvComments.setVisibility(View.VISIBLE);
            tvCommentNum.setText(String.valueOf(bean.getResult().getCount()));
            mAdapter.replaceData(bean.getResult().getData());
        } else {
            tvCommentNum.setText("0");
            rvComments.setVisibility(View.GONE);
        }
    }

    @Override
    public void onAddCartSuccess(MsgBean bean) {
        RxToast.success(bean.getMsg());
        orderSetBean = null;
        tvSpec.setText("");
        tv_btn_add_cart.getDelegate().setBackgroundColor(getResources().getColor(R.color.text_dddddd));
    }


    @OnClick({R.id.ll_btn_recruit_many, R.id.ll_btn_left, R.id.ll_btn_attr, R.id.ll_btn_spec, R.id.tv_btn_add_cart, R.id.tv_btn_bug})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_btn_recruit_many:
                //TODO 更多评论
                bundle = new Bundle();
                bundle.putInt("id", id);
                $startActivity(CommodityCommentListActivity.class, bundle);
                break;
            case R.id.ll_btn_left:
                finish();
                break;
            case R.id.ll_btn_attr:
                showParams();
                break;
            case R.id.ll_btn_spec:
                if (detailsInfoBean != null && detailsInfoBean.getResult().getSpec_arr().size() > 0) {
                    if (orderSetBean == null)
                        for (int i = 0; i < detailsInfoBean.getResult().getSpec_arr().size(); i++) {
                            for (int j = 0; j < detailsInfoBean.getResult().getSpec_arr().get(i).getSpec_item().size(); j++) {
                                detailsInfoBean.getResult().getSpec_arr().get(i).getSpec_item().get(j).setCheck(false);
                            }
                        }
                    isCartBug = 1;
                    showSpecifications();
                }
                break;
            case R.id.tv_btn_add_cart:
                // 加入 购物车
                if (orderSetBean != null) {
                    mPresenter.onAddCartData(LoginHelper.getLonginData().getResult(),
                            "add", id, spec_id, num);
                } else {
                    if (detailsInfoBean != null && detailsInfoBean.getResult().getSpec_arr().size() > 0) {
                        if (orderSetBean == null)
                            for (int i = 0; i < detailsInfoBean.getResult().getSpec_arr().size(); i++) {
                                for (int j = 0; j < detailsInfoBean.getResult().getSpec_arr().get(i).getSpec_item().size(); j++) {
                                    detailsInfoBean.getResult().getSpec_arr().get(i).getSpec_item().get(j).setCheck(false);
                                }
                            }
                        isCartBug = 2;
                        showSpecifications();
                    }
                }
                break;
            case R.id.tv_btn_bug:
                //TODO 购买
                if (orderSetBean != null) {
                    mPresenter.onOrderData(LoginHelper.getLonginData().getResult(),
                            "buy_now", id, spec_id, num);
                } else {
                    if (detailsInfoBean != null && detailsInfoBean.getResult().getSpec_arr().size() > 0) {
                        if (orderSetBean == null)
                            for (int i = 0; i < detailsInfoBean.getResult().getSpec_arr().size(); i++) {
                                for (int j = 0; j < detailsInfoBean.getResult().getSpec_arr().get(i).getSpec_item().size(); j++) {
                                    detailsInfoBean.getResult().getSpec_arr().get(i).getSpec_item().get(j).setCheck(false);
                                }
                            }
                        isCartBug = 1;
                        showSpecifications();
                    }
                }
                break;
        }
    }

    /**
     * 参数
     */
    private void showParams() {
        if (popupWindowParams != null && popupWindowParams.isShowing()) return;
        View upView = LayoutInflater.from(getMe()).inflate(R.layout.pw_commodity_params, null);
        //测量View的宽高
        CommonUtil.measureWidthAndHeight(upView);
        popupWindowParams = new CommonPopupWindow.Builder(getMe())
                .setView(R.layout.pw_commodity_params)
                .setWidthAndHeight(ViewGroup.LayoutParams.MATCH_PARENT, upView.getMeasuredHeight())
                .setBackGroundLevel(0.5f)//取值范围0.0f-1.0f 值越小越暗
                .setAnimationStyle(R.style.AnimUp)
                .setViewOnclickListener(this)
                .create();
        popupWindowParams.showAtLocation(findViewById(android.R.id.content), Gravity.BOTTOM, 0, 0);
    }

    /**
     * 规格
     */
    private void showSpecifications() {
        if (popupWindowSpecifications != null && popupWindowSpecifications.isShowing()) return;
        View upView = LayoutInflater.from(getMe()).inflate(R.layout.pw_commodity_spec, null);
        //测量View的宽高
        CommonUtil.measureWidthAndHeight(upView);
        popupWindowSpecifications = new CommonPopupWindow.Builder(getMe())
                .setView(R.layout.pw_commodity_spec)
                .setWidthAndHeight(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
                .setBackGroundLevel(0.5f)//取值范围0.0f-1.0f 值越小越暗
                .setAnimationStyle(R.style.AnimUp)
                .setViewOnclickListener(this)
                .create();
        popupWindowSpecifications.showAtLocation(findViewById(android.R.id.content), Gravity.BOTTOM, 0, 0);
    }

    ImageView commodity_img;
    TextView commodity_price;
    TextView tv_check_spec;
    TextView count;
    @Override
    public void getChildView(View view, int layoutResId) {
        switch (layoutResId) {
            case R.layout.pw_commodity_params:
                RecyclerView rvParams = view.findViewById(R.id.recyclerView);
                rvParams.setLayoutManager(new LinearLayoutManager(getMe()));
                rvParams.setNestedScrollingEnabled(false);
                //创建适配器
                CommodityParamsAdapter commodityParamsAdapter = new CommodityParamsAdapter(R.layout.pw_commodity_params_item, detailsInfoBean.getResult().getAttr_arr());
                //给RecyclerView设置适配器
                rvParams.setAdapter(commodityParamsAdapter);
                break;
            //todo 规格
            case R.layout.pw_commodity_spec:
                RoundTextView tv_btn_purchase = view.findViewById(R.id.tv_btn_purchase);
                commodity_img = view.findViewById(R.id.commodity_img);
                commodity_price = view.findViewById(R.id.commodity_price);
                count = view.findViewById(R.id.count);
                TextView commodity_title = view.findViewById(R.id.commodity_title);
                tv_check_spec = view.findViewById(R.id.tv_check_spec);
                TextView tvNum = view.findViewById(R.id.tv_num);
                tvNum.setText(String.valueOf(num));
                GlideUtil.ImageLoad(getMe(), detailsInfoBean.getResult().getSpec_img().get(0).getSpec_img(), commodity_img);
                commodity_price.setText("¥" + detailsInfoBean.getResult().getMoney());
                commodity_title.setText(detailsInfoBean.getResult().getTitle());

                RecyclerView rvSpec = view.findViewById(R.id.rv_spec);
                LinearLayoutManager layoutManager3 = new LinearLayoutManager(getMe());
                layoutManager3.setOrientation(LinearLayoutManager.VERTICAL);
                layoutManager3.setSmoothScrollbarEnabled(true);
                layoutManager3.setAutoMeasureEnabled(true);
                rvSpec.setLayoutManager(layoutManager3);
                rvSpec.setNestedScrollingEnabled(false);
                //创建适配器
                SpecArrAdapter mAdapter = new SpecArrAdapter(R.layout.pw_commodity_spec_title_list, detailsInfoBean.getResult().getSpec_arr());
                //给RecyclerView设置适配器
                rvSpec.setAdapter(mAdapter);
                view.findViewById(R.id.img_cancel).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        tvSpec.setText("长:" + custLengs + "/ 宽:" + et_width.getText().toString().trim() + " （x" + checkNum + ")");
                        popupWindowSpecifications.dismiss();
                    }
                });
                view.findViewById(R.id.img_btn_jian).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (num > 1) {
                            num--;
                            tvNum.setText(String.valueOf(num));
                        }

                    }
                });
                view.findViewById(R.id.img_btn_jia).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (store_count > 0) {
                            if (num < store_count) {
                                num++;
                                tvNum.setText(String.valueOf(num));
                            } else RxToast.error("库存不足");
                        } else RxToast.error("请先选择规格");
                    }
                });
                if (isCartBug == 1)
                    tv_btn_purchase.setText("提交订单");
                else tv_btn_purchase.setText("加入购物车");
                view.findViewById(R.id.tv_btn_purchase).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (orderSetBean != null) {
                            orderSetBean.setNum(num);
                            if (isCartBug == 1)
                                mPresenter.onOrderData(LoginHelper.getLonginData().getResult(),
                                        "buy_now", id, spec_id, num);
                            else mPresenter.onAddCartData(LoginHelper.getLonginData().getResult(),
                                    "add", id, spec_id, num);
                        } else RxToast.error("请先选择规格");

                    }
                });
                break;
        }
    }

    class SpecArrAdapter extends BaseQuickAdapter<DetailsInfoBean.ResultBean.SpecArrBean, BaseViewHolder> {
        Map<Integer, Integer> itemPos = new HashMap<>();
        Map<String, String> itemStrPos = new HashMap<>();

        public SpecArrAdapter(int layoutResId, @Nullable List<DetailsInfoBean.ResultBean.SpecArrBean> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, final DetailsInfoBean.ResultBean.SpecArrBean item) {

            TextView tv_type = helper.getView(R.id.tv_title);
            tv_type.setText(item.getName());

            RecyclerView recyclerView = helper.getView(R.id.rv_spec_items);
            FlowLayoutManager1 flowLayoutManager = new FlowLayoutManager1();
            //设置每一个item间距
            recyclerView.addItemDecoration(new SpaceItemDecoration(20));
            recyclerView.setLayoutManager(flowLayoutManager);
            SpecArrItemsAdapter mAdapter = new SpecArrItemsAdapter(R.layout.pw_commodity_spec_title_list_item, item.getSpec_item());
            recyclerView.setAdapter(mAdapter);
            mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
                @Override
                public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                    if (view.getId() == R.id.tv_title) {
                        if (mAdapter.getItem(position).isCheck()) {
                            item.getSpec_item().get(position).setCheck(false);
                            itemPos.put(item.getId(), -1);
                            itemStrPos.put(item.getName(), "");
                        } else {
                            for (int i = 0; i < item.getSpec_item().size(); i++) {
                                if (i == position) {
                                    item.getSpec_item().get(i).setCheck(true);
                                } else {
                                    item.getSpec_item().get(i).setCheck(false);
                                }
                            }
                            itemPos.put(item.getId(), item.getSpec_item().get(position).getId());
                            itemStrPos.put(item.getName(), item.getSpec_item().get(position).getItem());
                        }
                        mAdapter.notifyDataSetChanged();

                        List<Integer> ids = new ArrayList<>();
                        if (itemPos.size() == detailsInfoBean.getResult().getSpec_arr().size()) {
                            for (int key : itemPos.keySet()) {//keySet获取map集合key的集合  然后在遍历key即可
                                int value = itemPos.get(key);//
                                if (value > 0) {
                                    ids.add(value);
                                }
                            }
                            if (ids.size() == detailsInfoBean.getResult().getSpec_arr().size()) {
                                Collections.sort(ids);
                                String strIds = StringUtil.convertListToStringInt(ids);
                                for (int i = 0; i < detailsInfoBean.getResult().getSpec_img().size(); i++) {
                                    if (strIds.equals(detailsInfoBean.getResult().getSpec_img().get(i).getKey())) {
                                        GlideUtil.ImageLoad(getMe(), detailsInfoBean.getResult().getSpec_img().get(i).getSpec_img(), commodity_img);
                                        commodity_price.setText("¥" + detailsInfoBean.getResult().getSpec_img().get(i).getPrice() + "+" + detailsInfoBean.getResult().getIntegral() + "积分");
                                        count.setText("库存："+detailsInfoBean.getResult().getSpec_img().get(i).getStore_count() );
                                        store_count = detailsInfoBean.getResult().getSpec_img().get(i).getStore_count();
                                        spec_id = detailsInfoBean.getResult().getSpec_img().get(i).getId();
                                        StringBuffer sb = new StringBuffer();
                                        for (String key : itemStrPos.keySet()) {
                                            sb.append(itemStrPos.get(key) + ";");
                                        }
                                        tvSpec.setText(sb);
                                        tv_btn_add_cart.getDelegate().setBackgroundColor(getResources().getColor(R.color.main_color));
//                                        int id, String img, String title, String money, int num, String spec, String postag
                                        orderSetBean = new OrderSetBean(id, detailsInfoBean.getResult().getSpec_img().get(i).getSpec_img(),
                                                detailsInfoBean.getResult().getTitle(), detailsInfoBean.getResult().getSpec_img().get(i).getPrice() + "+" + detailsInfoBean.getResult().getIntegral() + "积分",
                                                num, sb.toString(), detailsInfoBean.getResult().getPostage(), detailsInfoBean.getResult().getSpec_img().get(i).getId(), "");
//                                        tv_check_spec.setText( detailsInfoBean.getResult().getSpec_img().get(i).);
                                    }
                                }
                            }
                        }
                    }
                }
            });


        }


    }
}
